package fr.montreuil.wargame.controller;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import fr.montreuil.wargame.domain.Role;
import fr.montreuil.wargame.domain.User;
import fr.montreuil.wargame.repository.UserRepository;

@Controller
@RequestMapping
public class AccessController {
	
	// Repository User dans la base
	@Resource
	UserRepository repository;

	@RequestMapping("/login")
	public String login(Model model, @RequestParam(required=false) String message) {
		model.addAttribute("message", message);
		return "access/login";
	}
	
	@RequestMapping(method=RequestMethod.GET, value="/register")
	public String register(Model model, @RequestParam(required=false) String message) {
		model.addAttribute("message", message);
		return "access/register";
	}
	
	/**
	 *********************************
	 ***	Controle du formulaire
	 *********************************
	 ***	@param username
	 ***	@param password
	 ***	@param password_confirm
	 ***	@param firstName
	 ***	@param lastName
	 ***	@return String url
	 *********************************
	 ***	@date 	27/04/2012
	 ***	@author jgay
	 *********************************
	 */
	@RequestMapping(method=RequestMethod.POST, value="/register")
	public String register(@RequestParam String username,
							@RequestParam String password,
							@RequestParam String password_confirm,
							@RequestParam String firstname,
							@RequestParam String lastname) {
		String message = "";
		
		// Si le username est vide
		if(username.isEmpty() || username == ""){
			message = "Username vide !";
		// Si le poassword est vide
		}else if(password.isEmpty() || password == ""){
			message = "Password vide !";
		// Si le password de confirmation est vide
		}else if(password_confirm.isEmpty() || password_confirm == ""){
			message = "Password Confirm vide !";
		// Si le pawword ne correspond pas au password de confirmation
		}else if(!password.equals(password_confirm)){
			message = "Password differant de Password Confirm !";
		// Si le firstname est vide
		}else if(firstname.isEmpty() || firstname == ""){
			message = "FirstName vide !";
		// Si le lastname est vide
		}else if(lastname.isEmpty() || lastname == ""){
			message = "LastName vide !";
		}
		
		// Récuperation d'un user avec l'username
		User exist = repository.findByUsername(username);
		// Si il est deja utiliser
		if(exist != null){
			message = "Username déjà utilisé !";
		}
			
		// Si il n'y a aucune erreur
		if(message.isEmpty()){
			// Creation de l'user en base
			User user = new User();
			user.setFirstName(firstname);
			user.setLastName(lastname);
			user.setPassword(getEncodedPassword(password_confirm));
			user.setUsername(username);
			user.setRole(new Role());
			user.getRole().setRole(2);
			user.getRole().setUser(user);
			// Insertion en base
			repository.save(user);
			
			// Redirection
			return "redirect:/register/success";
		// Si il y a une erreur
		}else{
			return "redirect:/register?message="+message;
		}
	}
	
	@RequestMapping(value = "/denied")
 	public String denied() {
		return "access/denied";
	}
	
	@RequestMapping(value = "/login/failure")
 	public String loginFailure() {
		String message = "Login Failure!";
		return "redirect:/login?message="+message;
	}
	
	@RequestMapping(value = "/logout/success")
 	public String logoutSuccess() {
		String message = "Logout Success!";
		return "redirect:/login?message="+message;
	}
	
	/**
	 *********************************
	 ***	Inscription reussi
	 *********************************
	 ***	@return String url
	 *********************************
	 ***	@date 	27/04/2012
	 ***	@author jgay
	 *********************************
	 */
	@RequestMapping(value = "/register/success")
 	public String registerSuccess() {		
		String message = "Register Success!";
		return "redirect:/login?message="+message;
	}
	
	/**
	 *********************************
	 ***	Crypte un password en md5
	 *********************************
	 ***	@param key
	 ***	@return String encoded_key
	 *********************************
	 ***	@date 	27/04/2012
	 ***	@author jgay
	 *********************************
	 */
	private static String getEncodedPassword(String key) {
		  byte[] uniqueKey = key.getBytes();
		  byte[] hash = null;
		  try {
			hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
		  } catch (NoSuchAlgorithmException e) {
			throw new Error("no MD5 support in this VM");
		  }
		  StringBuffer hashString = new StringBuffer();
		  for ( int i = 0; i < hash.length; ++i ) {
			String hex = Integer.toHexString(hash[i]);
			if ( hex.length() == 1 ) {
			  hashString.append('0');
			  hashString.append(hex.charAt(hex.length()-1));
			} else {
			  hashString.append(hex.substring(hex.length()-2));
			}
		  }
		  return hashString.toString();
		}
}